package com.ssm.plus.controller;

import com.ssm.plus.storage.StorageFileNotFoundException;
import com.ssm.plus.storage.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    StorageService storageService;

    @GetMapping("/list")
    @ResponseBody
    public Object listUploadedFiles() {

        return null;
//                storageService.loadAll().map(path -> {
//            String filename = path.getFileName().toString();
//            return MvcUriComponentsBuilder
//                    .fromMethodName(FileUploadController.class, "serveFile", filename)
//                    .build();
//        }).collect(Collectors.toList());


    }

    @GetMapping("/download/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);
//        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
        return null;
    }

    @PostMapping(value = "/upload")
    @ResponseBody
    public String handleFileUpload(@RequestPart(required = true) MockMultipartFile file) {
        storageService.store(file);
        return "/file/download/" + file.getOriginalFilename();
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
//        return ResponseEntity.notFound().build();
        return null;
    }

}
